package edu.xlh.travel.config;

import edu.xlh.travel.common.GalleryInRedisConstant;
import edu.xlh.travel.enumeration.SFTPOperateTypeEnum;
import edu.xlh.travel.util.FTPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Set;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTaskConfig implements SchedulingConfigurer {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = "0 */5 * * * ?";
                    //2.2 合法性校验.
                    if (!StringUtils.isEmpty(cron)) {
                        // Omitted Code  = ..

                        //Set<String> set1 = jedisPool.getResource().smembers(GalleryInRedisConstant.Gallery_RD_RESOURCES);
                        redisTemplate.setKeySerializer(new StringRedisSerializer());
                        redisTemplate.setValueSerializer(new StringRedisSerializer());
                        Set members = redisTemplate.opsForSet().difference(GalleryInRedisConstant.Gallery_RD_RESOURCES,
                                GalleryInRedisConstant.Gallery_DB_RESOURCES);
                        /*Set<String> set =jedisPool.getResource().sdiff(GalleryInRedisConstant.Gallery_RD_RESOURCES,
                                GalleryInRedisConstant.Gallery_DB_RESOURCES);*/
                        Iterator<String> iterator = members.iterator();
                        // 迭代删除多出来的垃圾图片
                        while (iterator.hasNext()) {
                            // 多出来的图片
                            String pic = iterator.next();
                            System.out.println("删除图片的名字===" + pic);
                            try {
                                FTPUtil.sshSftp(null , pic , SFTPOperateTypeEnum.rm.getCode());
                                redisTemplate.opsForSet().remove(GalleryInRedisConstant.Gallery_RD_RESOURCES , pic);
                            } catch (Exception e) {
                            }
                        }
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }

    //解决springboot + quartz + websocket (spring 自带得websocket 模块) 引起的冲突问题
    @Bean
    @Nullable
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
        threadPoolScheduler.setThreadNamePrefix("SockJS-");
        threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        threadPoolScheduler.setRemoveOnCancelPolicy(true);
        return threadPoolScheduler;
    }
}
